<template>
  <div 
    class="image-upload-container"
    @dragenter.prevent
    @dragover.prevent
    @drop.prevent
  >
    <!-- 图片上传封装结构 -->
    <div v-for="(item, index) in imgbox" :key="index" class="img-group">
      <div class="img-title">
        <span v-if="item.bitian === 1" class="required">*</span>
        {{ item.cn_name }}
        <span v-if="item.imglist && item.imglist.length > 0" class="count-badge">
          ({{ item.imglist.length }})
        </span>
      </div>
      
      <div class="img-box">
        <!-- 已上传的图片列表 -->
        <div 
          v-for="(img, imgIndex) in item.imglist" 
          :key="`img_${imgIndex}`" 
          class="img-item"
          @click="previewImage(item, imgIndex)"
        >
          <el-image
            :src="getImageUrl(img)"
            :preview-src-list="getPreviewList(item)"
            :initial-index="imgIndex"
            fit="contain"
            class="uploaded-image"
            lazy
          />
          <!-- 图片编号显示 -->
          <div class="img-number">{{ imgIndex + 1 }}</div>
          <!-- 删除按钮 -->
          <div 
            v-if="item.eidt > 0" 
            class="delete-btn"
            @click.stop="deleteImage(imgIndex, item)"
          >
            <el-icon><Close /></el-icon>
          </div>
          <!-- GPS信息显示 -->
          <div v-if="img.gps_info" class="gps-info">
            <el-icon><Location /></el-icon>
          </div>
        </div>
        
        <!-- 添加图片按钮（支持拖拽） -->
        <div 
          v-if="item.eidt > 0" 
          class="add-image-btn"
          :class="{ 'drag-over': dragStates[index] }"
          @click="chooseImage(item, index)"
          @dragenter.prevent.stop="handleDragEnter(index)"
          @dragover.prevent.stop="handleDragOver(index)"
          @dragleave.prevent.stop="handleDragLeave(index)"
          @drop.prevent.stop="handleDrop($event, item, index)"
        >
          <el-icon class="add-icon">
            <Plus />
          </el-icon>
          <div class="add-text">
            {{ dragStates[index] ? '释放以上传图片' : '点击或拖拽添加图片' }}
          </div>
        </div>
      </div>
      
      <!-- 图片说明或提示 -->
      <div v-if="item.z_tishi" class="img-tips">
        {{ item.z_tishi }}
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Plus, Close, Location } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { Base64 } from 'js-base64'

export default {
  name: 'ImageUpload',
  components: {
    Plus,
    Close,
    Location
  },
  props: {
    imgs: {
      type: Array,
      default: () => []
    },
    obj: {
      type: Object,
      default: () => ({})
    },
    imgUrl: {
      type: String,
      default: ''
    },
    faid: {
      type: Number,
      default: 0
    },
    isGps: {
      type: Boolean,
      default: false
    },
    uploadType: {
      type: String,
      default: 'general'
    }
  },
  emits: ['child-event', 'upload-success', 'upload-error'],
  setup(props, { emit }) {
    const imgbox = ref([])
    const dragStates = ref({}) // 拖拽状态管理
    
    // 监听props.imgs的变化
    watch(
      () => props.imgs,
      (newVal) => {
        console.log('ImageUpload 接收到的imgs数据:', newVal)
        imgbox.value = newVal || []
        // 初始化拖拽状态
        dragStates.value = {}
      },
      { immediate: true, deep: true }
    )
    
    // 获取预览图片列表
    // 获取图片URL（处理拼接图片的情况）
    const getImageUrl = (img) => {
      // 返回大图优先，避免缩略图拼接问题
      return img.datu || img.suoluet || ''
    }
    
    // 获取预览列表
    const getPreviewList = (item) => {
      if (!item.imglist || item.imglist.length === 0) return []
      // 对于预览，始终使用大图，避免缩略图拼接问题
      return item.imglist.map(img => img.datu || img.suoluet || '')
    }
    
    // 获取GPS信息
    const getGPSInfo = async () => {
      try {
        if (navigator.geolocation) {
          return new Promise((resolve, reject) => {
            navigator.geolocation.getCurrentPosition(
              position => {
                resolve({
                  latitude: position.coords.latitude,
                  longitude: position.coords.longitude,
                  accuracy: position.coords.accuracy,
                  timestamp: Date.now()
                })
              },
              error => {
                console.warn('获取GPS信息失败:', error)
                resolve(null)
              }
            )
          })
        }
        return null
      } catch (error) {
        console.warn('GPS获取异常:', error)
        return null
      }
    }
    
    // 选择图片 - 完全参考uni-app的chooseImage封装
    const chooseImage = async (item, index) => {
      console.log('选择图片:', item, index)
      
      try {
        if (item.ctype === 'img') {
          // 标准图片上传
          const input = document.createElement('input')
          input.type = 'file'
          input.accept = 'image/*'
          input.multiple = item.duotu == 1 // 支持多图上传
          
          input.onchange = async (e) => {
            const files = Array.from(e.target.files)
            if (files.length === 0) return
            
            const loading = ElLoading.service({
              lock: true,
              text: '正在上传图片...',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            
            try {
              for (const file of files) {
                await uploadSingleImage(item, file, index)
              }
              ElMessage.success('图片上传成功')
            } catch (error) {
              console.error('图片上传失败:', error)
              ElMessage.error('图片上传失败')
              emit('upload-error', error)
            } finally {
              loading.close()
            }
          }
          
          input.click()
        } else {
          // 生成图片编号 - 参考uni-app的编号生成逻辑
          let imgbianhao = ''
          const objs = JSON.parse(JSON.stringify(props.obj))
          const imgbhzd = JSON.parse(JSON.stringify(item.imgbhzd || []))
          
          imgbhzd.forEach(key => {
            if (key in objs) {
              if (imgbianhao === '') {
                imgbianhao = objs[key]
              } else {
                imgbianhao += '_' + objs[key]
              }
            }
          })
          
          const formData = {
            ctype: 'app_addtupian',
            imgleixing: '',
            shuiyin: '1',
            id: '0',
            tupianbt: '',
            zileix: item.en_name,
            leixingbh: imgbianhao,
            username: localStorage.getItem('username') || '',
            jiedaodizhi: '',
            jingweidu: '',
            faid: props.faid
          }
          
          if (props.isGps) {
            const gpsData = JSON.parse(localStorage.getItem('gps') || '{}')
            formData.jiedaodizhi = gpsData.jiedaodizhi || ''
            formData.jingweidu = gpsData.jingweidu || ''
          }
          
          console.log('地址信息:', formData)
          emit('child-event', formData, index)
        }
      } catch (error) {
        console.error('选择图片失败:', error)
        ElMessage.error('选择图片失败')
      }
    }
    
    // 上传单个图片 - 参考uni-app的uploadFile封装
    const uploadSingleImage = async (item, file, index) => {
      console.log('上传单个图片:', item, file)
      
      if (!file) {
        throw new Error('没有选择文件')
      }
      
      // 文件大小检查
      const maxSize = 10 * 1024 * 1024 // 10MB
      if (file.size > maxSize) {
        throw new Error('文件大小不能超过10MB')
      }
      
      // 文件类型检查
      const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
      if (!allowedTypes.includes(file.type)) {
        throw new Error('不支持的文件类型')
      }
      
      try {
        const formDataUpload = new FormData()
        formDataUpload.append('file', file)
        
        // 添加必要的请求参数，参考截图中的参数
        formDataUpload.append('ctype', 'app_shangchuan')
        formDataUpload.append('imgleixing', '')
        formDataUpload.append('shuiyin', '1')
        formDataUpload.append('id', '0')
        formDataUpload.append('tupianbt', item.cn_name || '附件图片')
        formDataUpload.append('zileix', item.en_name || '')
        formDataUpload.append('leixingbh', new Date().getTime().toString())
        formDataUpload.append('username', localStorage.getItem('username') || '')
        formDataUpload.append('openid', localStorage.getItem('openid') || "17526600083063721157")
        formDataUpload.append('bumenbh', localStorage.getItem('bumenbh') || '0001')
        formDataUpload.append('faid', props.faid.toString())
        
        // 如果需要GPS信息
        if (props.isGps) {
          const gpsInfo = await getGPSInfo()
          if (gpsInfo) {
            formDataUpload.append('jingweidu', JSON.stringify(gpsInfo))
            formDataUpload.append('jiedaodizhi', gpsInfo.address || '')
          } else {
            formDataUpload.append('jingweidu', '')
            formDataUpload.append('jiedaodizhi', '')
          }
        }
        
        // 使用具体的上传接口地址
        const uploadUrl = 'https://vue.haozskj.com/xcx/ajax/imgUpload_zj.ashx'
        const res = await request.post(uploadUrl, formDataUpload, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        
        if (res && res.leixing === 'ok') {
          // 构造图片对象，完全参考uni-app的结构
          const imageObj = {
            // 优先使用服务器返回的完整图片路径，避免拼接问题
            suoluet: res.suoluet || res.url || res.data?.url || '',
            // 对于大图，确保使用原始完整路径，不使用缩略图
            datu: res.datu || res.imgpath || res.url || res.data?.url || '',
            gps_info: res.gps_info || null,
            upload_time: new Date().toISOString(),
            file_name: file.name,
            file_size: file.size,
            // 保存完整响应，以便调试
            response: res
          }
          
          // 添加到图片列表
          if (!item.imglist) {
            item.imglist = []
          }
          item.imglist.push(imageObj)
          
          // 触发事件通知父组件
          emit('child-event', {
            type: 'upload',
            item: item,
            imageObj: imageObj,
            index: index
          })
          
          emit('upload-success', {
            item: item,
            imageObj: imageObj,
            result: res
          })
          
          return imageObj
        } else {
          throw new Error(res?.msg || '图片上传失败')
        }
      } catch (error) {
        console.error('上传图片失败:', error)
        throw error
      }
    }
    
    // 删除图片
    const deleteImage = async (imgIndex, item) => {
      try {
        await ElMessageBox.confirm('确定要删除这张图片吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        if (item.imglist && item.imglist.length > imgIndex) {
          const deletedImage = item.imglist[imgIndex]
          item.imglist.splice(imgIndex, 1)
          
          // 触发事件通知父组件
          emit('child-event', {
            type: 'delete',
            item: item,
            deletedImage: deletedImage,
            index: imgIndex
          })
          
          ElMessage.success('图片删除成功')
        }
      } catch (error) {
        console.log('取消删除')
      }
    }
    
    // 预览图片
    const previewImage = (item, imgIndex) => {
      console.log('预览图片:', item, imgIndex)
      if (item.imglist && item.imglist[imgIndex]) {
        const img = item.imglist[imgIndex];
        console.log('预览图片URL:', img.datu || img.suoluet);
        console.log('完整响应数据:', img.response);
        // Element Plus 的 el-image 组件会自动处理预览
      }
    }

    // 拖拽处理函数
    const handleDragEnter = (index) => {
      dragStates.value[index] = true
    }

    const handleDragOver = (index) => {
      dragStates.value[index] = true
    }

    const handleDragLeave = (index) => {
      dragStates.value[index] = false
    }

    const handleDrop = async (event, item, index) => {
      console.log('handleDrop 触发:', event, item, index)
      dragStates.value[index] = false
      
      const files = Array.from(event.dataTransfer.files)
      console.log('拖拽文件数量:', files.length)
      
      if (files.length === 0) {
        console.log('没有文件被拖拽')
        return
      }
      
      // 过滤只保留图片文件
      const imageFiles = files.filter(file => {
        console.log('文件类型:', file.type, '文件名:', file.name)
        return file.type.startsWith('image/')
      })
      
      console.log('图片文件数量:', imageFiles.length)
      
      if (imageFiles.length === 0) {
        ElMessage.warning('请拖拽图片文件')
        return
      }

      if (item.ctype === 'img') {
        // 标准图片上传
        const loading = ElLoading.service({
          lock: true,
          text: '正在上传图片...',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        
        try {
          // 如果不支持多图，只取第一个文件
          const filesToUpload = item.duotu == 1 ? imageFiles : [imageFiles[0]]
          console.log('准备上传的文件数量:', filesToUpload.length)
          
          for (const file of filesToUpload) {
            console.log('正在上传文件:', file.name)
            await uploadSingleImage(item, file, index)
          }
          ElMessage.success('图片上传成功')
        } catch (error) {
          console.error('图片上传失败:', error)
          ElMessage.error('图片上传失败')
          emit('upload-error', error)
        } finally {
          loading.close()
        }
      } else {
        console.log('不支持的上传类型:', item.ctype)
        ElMessage.info('此类型不支持拖拽上传，请点击添加')
      }
    }
    
    return {
      imgbox,
      dragStates,
      getImageUrl,
      getPreviewList,
      chooseImage,
      uploadSingleImage,
      deleteImage,
      previewImage,
      handleDragEnter,
      handleDragOver,
      handleDragLeave,
      handleDrop
    }
  }
}
</script>

<style scoped>
.image-upload-container {
  width: 100%;
}

.img-group {
  width: 100%;
  margin-bottom: 20px;
}

.img-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #333;
}

.required {
  color: #f56c6c;
  margin-right: 4px;
}

.count-badge {
  color: #409eff;
  font-size: 12px;
  margin-left: 4px;
}

.img-box {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: flex-start;
}

.img-item {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  border: 1px solid #ddd;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.img-number {
  position: absolute;
  top: 2px;
  left: 2px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  font-size: 10px;
  padding: 1px 4px;
  border-radius: 2px;
  line-height: 1;
}

.delete-btn {
  position: absolute;
  top: 2px;
  right: 2px;
  background: rgba(255, 0, 0, 0.8);
  color: white;
  border-radius: 50%;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 12px;
}

.delete-btn:hover {
  background: rgba(255, 0, 0, 1);
}

.gps-info {
  position: absolute;
  bottom: 2px;
  right: 2px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  border-radius: 2px;
  padding: 1px;
  font-size: 10px;
}

.add-image-btn {
  width: 80px;
  height: 80px;
  border: 2px dashed #ddd;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #999;
  transition: all 0.3s;
}

.add-image-btn:hover {
  border-color: #409eff;
  color: #409eff;
}

/* 拖拽状态样式 */
.add-image-btn.drag-over {
  border-color: #67c23a;
  background-color: rgba(103, 194, 58, 0.1);
  color: #67c23a;
  transform: scale(1.02);
}

.add-icon {
  font-size: 20px;
  margin-bottom: 4px;
}

.add-text {
  font-size: 12px;
  text-align: center;
  line-height: 1.2;
}

.img-tips {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
  line-height: 1.4;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .img-item,
  .add-image-btn {
    width: 60px;
    height: 60px;
  }
  
  .add-text {
    font-size: 10px;
  }
}
</style>